// 章节目录
const chapters = [
    // 凡境篇（1-200章）
    // 第一阶段：混沌觉醒（1-10章）
    { id: 1, title: "灵根觉醒", file: "chapter1.txt" },
    { id: 2, title: "混沌之气", file: "chapter2.txt" },
    { id: 3, title: "入门考核", file: "chapter3.txt" },
    { id: 4, title: "混元天门", file: "chapter4.txt" },
    { id: 5, title: "修炼开始", file: "chapter5.txt" },
    { id: 6, title: "灵气漩涡", file: "chapter6.txt" },
    { id: 7, title: "第一次突破", file: "chapter7.txt" },
    { id: 8, title: "神秘符文", file: "chapter8.txt" },
    { id: 9, title: "真相浮现", file: "chapter9.txt" },
    { id: 10, title: "混沌之路", file: "chapter10.txt" },

    // 第二阶段：营救母亲（11-20章）
    { id: 11, title: "混元动荡", file: "chapter11.txt" },
    { id: 12, title: "太虚探索", file: null },
    { id: 13, title: "魔域威胁", file: null },
    { id: 14, title: "联盟会议", file: null },
    { id: 15, title: "封印之谜", file: null },
    { id: 16, title: "血脉觉醒", file: null },
    { id: 17, title: "道统传承", file: null },
    { id: 18, title: "破阵而出", file: null },
    { id: 19, title: "重逢之战", file: null },
    { id: 20, title: "母子相见", file: null },

    // 第三阶段：宗门崛起（21-50章）
    { id: 21, title: "重建宗门", file: null },
    { id: 22, title: "招收弟子", file: null },
    { id: 23, title: "建立联盟", file: null },
    // ... 更多章节待添加 ...

    // 后续章节将按照新的规划逐步添加
    // 凡境篇（继续到200章）
    // 仙境篇（201-600章）
    // 神境篇（601-1000章）
    // 混沌篇（1001-1500章）
    // 超脱篇（1501-2000章）
];

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', () => {
    // 检测是否为移动设备
    const isMobile = window.matchMedia("(max-width: 768px)").matches;

    // 获取DOM元素
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const customSelect = document.querySelector('.custom-select');
    const selectHeader = document.querySelector('.select-header');
    const selectedChapter = document.getElementById('selectedChapter');
    const chapterList = document.getElementById('chapterList');
    const closeBtn = document.querySelector('.mobile-select-close');
    const chapterTitle = document.getElementById('chapterTitle');
    const storyContent = document.getElementById('storyContent');

    // 获取底部控制元素
    const prevBtnBottom = document.getElementById('prevBtnBottom');
    const nextBtnBottom = document.getElementById('nextBtnBottom');

    // 获取顶部控制栏元素
    const topControls = document.querySelector('.controls:not(.bottom-controls)');
    const bottomControls = document.querySelector('.bottom-controls');

    // 当前章节
    let currentChapter = 1;

    // 检查顶部控制栏是否在视口中
    function isTopControlsVisible() {
        const rect = topControls.getBoundingClientRect();
        const windowHeight = window.innerHeight || document.documentElement.clientHeight;
        return rect.top > -50 && rect.bottom < (windowHeight + 50);
    }

    // 处理滚动事件
    function handleScroll() {
        const shouldShowBottom = !isTopControlsVisible();
        bottomControls.style.display = shouldShowBottom ? 'flex' : 'none';
    }

    // 添加滚动事件监听
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', handleScroll);

    // 初始检查
    handleScroll();

    // 更新章节选择状态
    function updateChapterSelection() {
        document.querySelectorAll('.select-option').forEach(option => {
            const chapter = parseInt(option.dataset.chapter);
            option.classList.toggle('selected', chapter === currentChapter);
        });

        // 关闭下拉菜单
        customSelect.classList.remove('open');
    }

    // 更新章节显示
    function updateChapterDisplay() {
        selectedChapter.textContent = `第${currentChapter}章：${chapters[currentChapter - 1].title}`;

        // 更新按钮状态
        prevBtn.disabled = currentChapter === 1;
        nextBtn.disabled = currentChapter === chapters.length;
        prevBtnBottom.disabled = currentChapter === 1;
        nextBtnBottom.disabled = currentChapter === chapters.length;
    }

    // 加载章节内容
    async function loadChapter() {
        if (currentChapter < 1 || currentChapter > chapters.length) {
            return;
        }

        const chapter = chapters[currentChapter - 1];

        // 更新标题
        chapterTitle.textContent = `第${chapter.id}章：${chapter.title}`;

        // 更新内容
        try {
            if (chapter.file) {
                const response = await fetch(`chapters/${chapter.file}`);
                if (response.ok) {
                    const content = await response.text();
                    storyContent.innerHTML = content
                        .split('\n')
                        .map(line => line.trim())
                        .filter(line => line)
                        .map(line => `<p>${line}</p>`)
                        .join('');
                } else {
                    throw new Error('Failed to load chapter');
                }
            } else {
                throw new Error('Chapter not available');
            }
        } catch (error) {
            storyContent.innerHTML = '<p>本章节正在创作中...</p>';
        }

        // 更新选中状态
        updateChapterSelection();
        updateChapterDisplay();
    }

    // 关闭下拉菜单
    function closeDropdown() {
        customSelect.classList.remove('open');
        // 延迟一下再恢复滚动，确保下拉菜单完全关闭
        setTimeout(() => {
            document.body.style.position = '';
            document.body.style.overflow = 'auto';
            document.body.style.overflowY = 'auto';
            document.body.style.height = '';
        }, 100);
    }

    // 打开下拉菜单
    function openDropdown() {
        customSelect.classList.add('open');
        if (isMobile) {
            document.body.style.position = 'fixed';
            document.body.style.overflow = 'hidden';
            document.body.style.height = '100%';
            document.body.style.width = '100%';
        }
    }

    // 切换下拉菜单
    selectHeader.addEventListener('click', (e) => {
        e.stopPropagation();
        if (customSelect.classList.contains('open')) {
            closeDropdown();
        } else {
            openDropdown();
        }
    });

    // 移动端点击遮罩层或关闭按钮关闭下拉菜单
    if (isMobile && closeBtn) {
        closeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            closeDropdown();
        });

        document.addEventListener('click', (e) => {
            if (customSelect.classList.contains('open') &&
                !e.target.closest('.select-options') &&
                !e.target.closest('.select-header')) {
                closeDropdown();
            }
        });
    } else {
        // PC端点击外部关闭下拉菜单
        document.addEventListener('click', (e) => {
            if (!customSelect.contains(e.target)) {
                closeDropdown();
            }
        });
    }

    // 初始化章节列表
    function initChapterList() {
        const selectOptions = document.querySelector('.select-options');
        selectOptions.innerHTML = '';

        chapters.forEach(chapter => {
            const option = document.createElement('div');
            option.className = 'select-option';
            option.dataset.chapter = chapter.id;
            option.textContent = `第${chapter.id}章：${chapter.title}`;
            option.addEventListener('click', () => {
                currentChapter = chapter.id;
                loadChapter();
                updateChapterSelection();
                closeDropdown();
                // 强制启用滚动
                document.body.style.position = '';
                document.body.style.overflow = 'auto';
                document.body.style.overflowY = 'auto';
                document.body.style.height = '';
                document.body.style.width = '';
            });
            selectOptions.appendChild(option);
        });
    }

    // 为底部按钮添加事件监听器
    prevBtnBottom.addEventListener('click', () => {
        if (currentChapter > 1) {
            currentChapter--;
            loadChapter();
            window.scrollTo(0, 0);
        }
    });

    nextBtnBottom.addEventListener('click', () => {
        if (currentChapter < chapters.length) {
            currentChapter++;
            loadChapter();
            window.scrollTo(0, 0);
        }
    });

    // 添加事件监听器
    prevBtn.addEventListener('click', () => {
        if (currentChapter > 1) {
            currentChapter--;
            loadChapter();
        }
    });

    nextBtn.addEventListener('click', () => {
        if (currentChapter < chapters.length) {
            currentChapter++;
            loadChapter();
        }
    });

    // 初始化页面
    initChapterList();
    loadChapter();
});
